package com.lsz.atm.ui.pay;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.common.CountDownUtlis;
import com.common.config.Constant;
import com.common.mvp.BaseMvpActivity;
import com.common.thirdparty.ThirdParty;
import com.common.thirdparty.aiyin.AiYinParty;
import com.common.thirdparty.sdkUtil.QRCodeTypeUtils;
import com.common.util.ASCIIUtil;
import com.common.util.ObjectUtil;
import com.common.util.RandomUtil;
import com.facebook.stetho.common.LogUtil;
import com.google.gson.Gson;
import com.lsz.atm.R;
import com.lsz.atm.TemporaryDataUtil;
import com.lsz.atm.db.dao_utils.DaoUtils;
import com.lsz.atm.dialog.ConfirmDialog;
import com.lsz.atm.event.StartOrderEvent;
import com.lsz.atm.json.ATMBean;
import com.lsz.atm.json.OrderBean;
import com.lsz.atm.json.OrderPayBean;
import com.lsz.atm.json.PayRequestBean;
import com.lsz.atm.json.commodity.ProposalsBean;
import com.lsz.atm.ui.order.OrderListActivity;
import com.util_code.BuildConfig;
import com.util_code.utils.AndroidUtils;
import com.util_code.utils.DateUtils;
import com.util_code.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import okhttp3.RequestBody;
import print.Print;

public class PayActivity extends BaseMvpActivity<PayView, PayPresent> implements PayView, View.OnClickListener {

    @BindView(R.id.tv_pay_type)
    TextView tvPayType;
    @BindView(R.id.tv_pay_hint)
    TextView tvPayHint;
    @BindView(R.id.pay_order_cancel)
    Button payOrderCancel;

    @BindView(R.id.tv_pay_schedule)
    TextView tvPaySchedule;
    @BindView(R.id.tv_pay_schedule1)
    TextView tvPaySchedule1;
    @BindView(R.id.loading)
    ProgressBar loading;

    private ConfirmDialog confirmDialog;
    private CountDownUtlis countDownUtlis;
    private OrderBean orderBean;

    /**
     * 付款码
     */
    private StringBuilder sb = new StringBuilder();
    private boolean extractQrCode = true;
    private Handler mHandler = new Handler();
    private PayRequestBean payRequest;
    private boolean timeOut = true;

    public static void startActivity(Activity activity, OrderBean orderBean) {
        ThirdParty.checkIsOpened();
        Intent intent = new Intent(activity, PayActivity.class);
        Bundle bundle = new Bundle();
        bundle.putParcelable("OrderBean", orderBean);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_pay;
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void setupView() {
        payOrderCancel.setOnClickListener(this);
        countDownUtlis = new CountDownUtlis(getMvpView());
    }

    @Override
    protected void setupData(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        Intent intent = getIntent();
        orderBean = intent.getParcelableExtra("OrderBean");

        payRequest = new PayRequestBean();
        tvPaySchedule1.setText(getResources().getString(R.string.pay_processing));
        tvPaySchedule1.setVisibility(View.INVISIBLE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.pay_order_cancel:
                ConfirmDialog.Builder builder = new ConfirmDialog.Builder(PayActivity.this);
                confirmDialog = builder.setContentText("是否取消订单").setConfirmListener(new ConfirmDialog.Builder.ConfirmClickListener() {
                    @Override
                    public void click(boolean b) {
                        confirmDialog.dismiss();
                        if (b) {
                            DaoUtils.getCommodityInstance().deleteAll();
                            DaoUtils.getPackageInstance().deleteAll();
                            EventBus.getDefault().post(new StartOrderEvent());
                            finish();
                        }
                    }
                }).create();
                confirmDialog.show();
                break;
            default:
                break;
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        //键盘事件为back时，不监听
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            return super.dispatchKeyEvent(event);
        } else {
            return handleKeyEvent(event);
        }
    }

    private boolean handleKeyEvent(KeyEvent event) {
        int action = event.getAction();
        LogUtil.d("event" + event);
        switch (action) {
            case KeyEvent.ACTION_DOWN:
                if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) {
                    return false;
                }
                if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) {
                    return false;
                }
                if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
                    return false;
                }
                if (event.getKeyCode() == KeyEvent.KEYCODE_MENU) {
                    return false;
                }
                if (event.getKeyCode() == KeyEvent.KEYCODE_HOME) {
                    return false;
                }
                if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
                    return false;
                }
                int unicodeChar = event.getUnicodeChar();
                sb.append((char) unicodeChar);
                LogUtil.d("扫码===" + (char) unicodeChar + "   " + sb.toString());
                if (extractQrCode) {
                    mHandler.postDelayed(this::spliceQrCode, 500);
                }
                return false;
            default:
                break;
        }
        return false;
    }

    /**
     * 拼接付款码
     */
    private void spliceQrCode() {
        if (extractQrCode && sb.length() > 0) {
            String qrCode = sb.toString().trim();
            LogUtil.e("qrCode    " + qrCode);
            int qrCodeType = QRCodeTypeUtils.checkQRCodeType(qrCode);
            if (qrCodeType != QRCodeTypeUtils.TYPE_NO) {
                //do something\
                loading.setVisibility(View.VISIBLE);
                tvPaySchedule1.setVisibility(View.VISIBLE);
                payOrderCancel.setVisibility(View.INVISIBLE);
                PayRequestBean requestBean = setPayData(qrCode, qrCodeType);
                getPresenter().payOrderSwipe(requestBean);
                countDownUtlis.countDown(60, countDownListener);
            }
            sb.setLength(0);
        }
    }

    private PayRequestBean setPayData(String qrCode, int qrCodeType) {
        PayRequestBean.BizContentBean bizContent = new PayRequestBean.BizContentBean();
        bizContent.attach = "订单: " + orderBean.id;
        bizContent.auth_code = qrCode;
//        ATMBean atmBean = new ATMBean();
//        bizContent.store_id = Integer.parseInt(atmBean.storeId);
//                bizContent.cashier_id = 151156;
        bizContent.discount_switch = 0;
        bizContent.merchant_order_sn = orderBean.orderSeq;
        if (BuildConfig.DEBUG) {
            bizContent.total_fee = 0.01f;
        } else {
            bizContent.total_fee = TextUtils.isEmpty(orderBean.amountActual) ? 0f : Float.parseFloat(orderBean.amountActual);
        }
        bizContent.type = qrCodeType;
        bizContent.call_back_url = orderBean.noticeUrl;
        bizContent.timeout_express = DateUtils.getDataAddTime(1);
//        bizContent.goods_tag = "";
//        bizContent.detail = getGoodDetail();
        JSONObject object = JSONObject.parseObject(JSONObject.toJSON(bizContent).toString());
        return setPayData(object, Constant.PAY_APP_METHOD);
    }

    private PayRequestBean setPayData(JSONObject object, String method) {
        payRequest.app_id = Constant.PAY_APP_ID;
        payRequest.method = method;
        payRequest.biz_content = object.toString();
        payRequest.format = "json";
        payRequest.sign_method = "md5";
        payRequest.nonce = RandomUtil.getRandomNumber();

        payRequest.version = AndroidUtils.getAppVersionName();
        payRequest.sign = null;

        Map<String, Object> objectToMap = ObjectUtil.objectToMap(payRequest);
        payRequest.sign = ASCIIUtil.getSign(objectToMap, Constant.PAY_APP_SECRET);
        return payRequest;
    }

    private PayRequestBean.Detail getGoodDetail() {
        PayRequestBean.Detail detail = new PayRequestBean.Detail();
        detail.cost_price = 1;
        detail.receipt_id = "";
        List<PayRequestBean.Detail.GoodsDetail> detailList = new ArrayList<>();
        PayRequestBean.Detail.GoodsDetail goodsDetail = new PayRequestBean.Detail.GoodsDetail();
        goodsDetail.goods_id = "";
        goodsDetail.goods_name = "";
        goodsDetail.quantity = 1;
        goodsDetail.price = 1;
        detailList.add(goodsDetail);
        detail.goods_detail = detailList;
        return detail;
    }

    private CountDownUtlis.CountDownListener countDownListener = new CountDownUtlis.CountDownListener() {

        @Override
        public void onCountStart() {
            tvPaySchedule.setText("60");
        }

        @Override
        public void onCountProgress(long progress) {
            tvPaySchedule.setText(progress + "");
        }

        @Override
        public void onCountEnd() {
            timeOut = false;
        }

        @Override
        public void onCountError() {
            timeOut = false;
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(StartOrderEvent event) {
        finish();
    }

    @Override
    public void onSuccess(OrderPayBean orderPayBean) {
        if (TextUtils.equals(orderPayBean.trade_state, "SUCCESS")) {
            getPresenter().getOrderStatus(orderPayBean.merchant_order_sn);
//            getPresenter().payOrderNotice(orderPayBean);
            PaySuccessActivity.startActivity(this, orderBean, orderPayBean.total_fee);
            loading.setVisibility(View.INVISIBLE);
            tvPaySchedule.setVisibility(View.INVISIBLE);
            tvPaySchedule1.setText(getResources().getString(R.string.pay_success));
            payOrderCancel.setVisibility(View.INVISIBLE);
        } else {
            if (timeOut) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("merchant_order_sn", orderPayBean.merchant_order_sn);
                PayRequestBean requestBean = setPayData(jsonObject, Constant.PAY_APP_QUERY);
                getPresenter().payOrderQuery(requestBean);
            } else {
            }
        }
    }

    @Override
    public void onStatusSuccess(boolean isTrue) {
//        if (isTrue) {
//            loading.setVisibility(View.INVISIBLE);
//            tvPaySchedule1.setVisibility(View.INVISIBLE);
//            payOrderCancel.setVisibility(View.INVISIBLE);
//            PaySuccessActivity.startActivity(this, orderBean);
//        } else {
//            if (timeOut) {
////                getPresenter().getOrderStatus(id);
//            } else {
//                ConfirmDialog.Builder builder = new ConfirmDialog.Builder(PayActivity.this);
//                confirmDialog = builder.setContentText("是否取消订单").setConfirmListener(new ConfirmDialog.Builder.ConfirmClickListener() {
//                    @Override
//                    public void click(boolean b) {
//                        confirmDialog.dismiss();
//                        if (b) {
//                            DaoUtils.getCommodityInstance().deleteAll();
//                            DaoUtils.getPackageInstance().deleteAll();
//                            EventBus.getDefault().post(new StartOrderEvent());
//                            finish();
//                        }
//                    }
//                }).create();
//                confirmDialog.show();
//            }
//        }
    }

    @Override
    public void onPayError(String sub_code) {
        loading.setVisibility(View.INVISIBLE);
        tvPaySchedule.setVisibility(View.INVISIBLE);
        tvPaySchedule1.setVisibility(View.INVISIBLE);
        payOrderCancel.setVisibility(View.VISIBLE);
        ToastUtils.showLongToast(sub_code);
        finish();
    }

    @Override
    public void onFail() {
        loading.setVisibility(View.INVISIBLE);
        tvPaySchedule.setVisibility(View.INVISIBLE);
        tvPaySchedule1.setVisibility(View.INVISIBLE);
        payOrderCancel.setVisibility(View.VISIBLE);
        String payContinueTimeout = getResources().getString(R.string.pay_continue_timeout);
        ConfirmDialog.Builder builder = new ConfirmDialog.Builder(PayActivity.this);
        builder.setContentText(payContinueTimeout);
        builder.setOkText("确认");
        builder.setOKVisibility(true);
        confirmDialog = builder.setConfirmListener(new ConfirmDialog.Builder.ConfirmClickListener() {
            @Override
            public void click(boolean b) {
                confirmDialog.dismiss();
                if (b) {
                    finish();
                }
            }
        }).create();
        confirmDialog.setCancelable(false);
        confirmDialog.show();
    }
}
